import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket;
    private String serverIP;
    private int serverPort;
    //跟服务器不同，客户端需要指定访问服务器的地址
    public UdpEchoClient(String serverIP,int serverPort) throws SocketException {
        this.serverIP=serverIP;
        this.serverPort=serverPort;
        socket=new DatagramSocket();
    }
    public void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入要发送的内容：");
        String request=scanner.next();
        //把请求发送给服务器，需要构造DatagramPacket对象
        //构造过程中不光要构造载荷，还要设置服务器的IP和端口号
        DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length,
                InetAddress.getByName(serverIP),serverPort);
        //发送数据包
        socket.send(requestPacket);
        //接收服务器的响应
        DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
        socket.receive(responsePacket);
        //从服务器读取的数据进行解析打印出来
        String response=new String(responsePacket.getData(),0,responsePacket.getLength());
        System.out.println(response);
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
